const Term = require("../obj/Term");
const fs = require("fs");
const fstream = require("fstream");
const zlib = require('zlib')
const tar = require('tar')

function fileToDb(mongoHandler) {
  read().then(arr => {
    mongoHandler.insertMany(arr).then(console.log)
  }).catch(err => {
    console.error("从文件同步到 mongo 失败：", err)
  })
}

function dbToFile(mongoHandler) {
  let time = new Date().getTime();
  const file = './data/backup/term_' + time + '.json';
  mongoHandler.find({}).toArray().then(arr => {
    let res = JSON.stringify(arr, null, 2);
    fs.writeFile(file, res, err => {
      err && console.error("从 mongo 同步到文件失败：", err)
    })
  })
}

function read() {
  return new Promise((resolve, reject) => {
    fs.readFile('./data/term.json', (err, buffer) => {
      if (!err) {
        try {
          let parse = JSON.parse(buffer.toString('utf-8'));
          console.log(parse.map(x => new Term(x)));
          resolve(parse.map(x => new Term(x)))
        } catch (e) {
          reject(e)
        }
      } else {
        reject(err)
      }
    })
  })
}

module.exports = {
  fileToDb, dbToFile
}
